package com.glodon.paas.util;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import com.glodon.paas.consts.StringConst;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Don Li
 */
public class HttpUtils {
    public static int getResponseCode(String url) throws IOException {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpclient.execute(httpGet);
            return response.getStatusLine().getStatusCode();
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

    public static void sendDelete(String url) throws IOException {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpDelete httpDelete = new HttpDelete(url);
            httpclient.execute(httpDelete);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
    
    public static boolean isAjaxRequest(HttpServletRequest request){
    	return StringConst.AJAX_HEADER_VALUE.equalsIgnoreCase(request.getHeader(StringConst.AJAX_HEADER));
    }
    
    public static boolean isMultiPartRequest(HttpServletRequest request){
    	return request.getHeader(HTTP.CONTENT_TYPE)!=null && request.getHeader(HTTP.CONTENT_TYPE).indexOf(StringConst.MULTIPART_HEADER)>=0;
    }
	
	public static String encodeUTF8(String str){
		try {
			return URLEncoder.encode(str, "UTF-8");
		} catch (Exception e) {
			return str;
		}
	}
}
